﻿namespace MicroCloud.Utils
{
    /// <summary>
    /// 时间片 <see cref="TimeSpan"/> 扩展方法
    /// </summary>
    public static class TimeSpanExtensions
    {
        /// <summary>
        /// 将时间片转换为X时X分X秒的格式
        /// </summary>
        /// <param name="ts"></param>
        /// <returns></returns>
        public static string ToTimeString(this TimeSpan ts)
        {
            string value = string.Empty;
            if (ts.Seconds > 0)
            {
                var secondsValue = $"{ts.Seconds:D2}";
                value += I18N.T("{0}秒", secondsValue);
            }

            if (ts.Minutes > 0)
            {
                value = I18N.T("{0}分{1}", ts.Minutes, value);
            }

            if (ts.Hours > 0)
            {
                value = I18N.T("{0}时{1}", ts.Hours, value);
            }

            if (ts.Days > 0)
            {
                value = I18N.T("{0}天{1}}", ts.Days, value);
            }

            return value;
        }

        /// <summary>
        /// 时间片倒计时
        /// </summary>
        /// <param name="ts"></param>
        /// <param name="action"></param>
        /// <param name="intervalMilliseconds"></param>
        public static void CountDown(this TimeSpan ts, Action<TimeSpan> action, int intervalMilliseconds = 1000)
        {
            while (ts > TimeSpan.Zero)
            {
                action(ts);
                TimeSpan ts2 = TimeSpan.FromMilliseconds(intervalMilliseconds);
                Thread.Sleep(ts2);
                ts = ts.Subtract(ts2);
            }
        }

        /// <summary>
        /// 时间片倒计时
        /// </summary>
        /// <param name="ts"></param>
        /// <param name="action"></param>
        /// <param name="intervalMilliseconds"></param>
        /// <returns></returns>
        public static async Task CountDownAsync(this TimeSpan ts, Func<TimeSpan, Task> action, int intervalMilliseconds = 1000)
        {
            while (ts > TimeSpan.Zero)
            {
                await action(ts);
                TimeSpan ts2 = TimeSpan.FromMilliseconds(intervalMilliseconds);
                await Task.Delay(ts2);
                ts = ts.Subtract(ts2);
            }
        }

    }

}
